package map;

import collection.set.User;
import org.junit.Test;

import java.util.Comparator;
import java.util.TreeMap;
import java.util.TreeSet;

/*
* TreeMap
* */
public class TreeMapTest {
    public static void main(String[] args) {
        //向Treemap中添加对象,要求key必须是同一个类的对象
        //因为要按照key进行排序:自然排序,定制排序
    }

    //自然排序
    @Test
    public void test1(){
        User u1 = new User("xiaoli", 12);
        User u2 = new User("xiaowang", 32);
        User u3 = new User("xiaozhang", 43);
        User u4 = new User("xiaozuo", 18);

        TreeMap map = new TreeMap();
        map.put(u1,43);
        map.put(u2,56);
        map.put(u3,876);
        map.put(u4,90);

        System.out.println(map);
    }

    //定制排序,按照年龄排序
    @Test
    public void test2(){
        User u1 = new User("xiaoli", 12);
        User u2 = new User("xiaowang", 32);
        User u3 = new User("xiaozhang", 43);
        User u4 = new User("xiaozuo", 18);

        TreeMap map = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o, Object t1) {
                if (o instanceof User && t1 instanceof User){
                    return Integer.compare(((User) o).getAge(),((User) t1).getAge());
                }
                return 0;
            }
        });
        map.put(u1,43);
        map.put(u2,56);
        map.put(u3,876);
        map.put(u4,90);

        System.out.println(map);
    }

}
